package com.hczx.caxa.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hczx.caxa.bean.ResultBean;
import com.hczx.caxa.service.LogFileService;
import com.hczx.caxa.service.TechnicalGeneratePdfService;

import io.swagger.annotations.Api;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Api(tags = "技术文件生成PDF")
@RestController()
@RequestMapping("/technicalGeneratePdf")
public class TechnicalGeneratePdfController {
    private static Logger logger = LoggerFactory.getLogger(TechnicalGeneratePdfController.class);

    final TechnicalGeneratePdfService pdfService;
    final LogFileService logFile;

    public TechnicalGeneratePdfController(TechnicalGeneratePdfService pdfService, LogFileService logFile) {
        this.pdfService = pdfService;
        this.logFile = logFile;
    }

    /**
     * 生成设计更改单PDF
     * @param infos
     * @param images
     * @return
     */
    @RequestMapping(value = "/generatePdf", method = RequestMethod.POST)
    public ResultBean doGeneratePdf(String infos, @RequestParam Map<String, MultipartFile> images) {
    	logger.info("infos:{}", infos);
    	String basicInfo = "";
    	String number = "";
		Object changeContent = "";
		String effect = "";
		String reason = "";
		Object signInfo = "";
		String sendDepartment = "";
		String model = "";
		String imageName = "";
    	// 将 JSON 字符串解析为 JSON 数组
        JSONArray jsonArray = JSONArray.parseArray(infos);
        // 遍历 JSON 数组并输出结果
        for (Object obj : jsonArray) {
            JSONObject json = (JSONObject) obj;
            for (String key : json.keySet()) {
            	if(StringUtils.equals(key, "basicInfo")) {
            		basicInfo = (String) json.get(key);
            	}else if(StringUtils.equals(key, "number")) {
            		number = (String) json.get(key);
            	}else if(StringUtils.equals(key, "changeContent")) {
            		changeContent = json.get(key);
            	}else if(StringUtils.equals(key, "effect")) {
            		effect = (String) json.get(key);
            	}else if(StringUtils.equals(key, "reason")) {
            		reason = (String) json.get(key);
            	}else if(StringUtils.equals(key, "signInfo")) {
            		signInfo = json.get(key);
            	}else if(StringUtils.equals(key, "sendDepartment")) {
            		sendDepartment = (String) json.get(key);
            	}else if(StringUtils.equals(key, "model")) {
            		model = (String) json.get(key);
            	}else if(StringUtils.equals(key, "imageName")) {
            		imageName = (String) json.get(key);
            	}
            }
        }
        ResultBean result = ResultBean.buildSuccessResult();
        logger.info("number:{}", number);
        logger.info("basicInfo:{}", basicInfo);
        logger.info("changeContent:{}", changeContent);
        logger.info("effect:{}", effect);
        logger.info("reason:{}", reason);
        logger.info("signInfo:{}", signInfo);
        logger.info("sendDepartment:{}", sendDepartment);
        logger.info("model:{}", model);
        logger.info("imageName:{}", imageName);
        StringBuffer loggerBuffer = new StringBuffer();
        loggerBuffer.append(logFile.now()).append("----->生成PDF开始<-----").append("\n");
        loggerBuffer.append(logFile.now()).append("  -->number:").append(number).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->basicInfo:").append(basicInfo).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->effect:").append(effect).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->reason:").append(reason).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->sendDepartment:").append(sendDepartment).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->model:").append(model).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->imageName:").append(imageName).append("\n");
        
        for (Map.Entry<String, MultipartFile> entry : images.entrySet()) {
            String paramName = entry.getKey(); // 获取参数名
            MultipartFile image = entry.getValue(); // 获取文件对象
            loggerBuffer.append(logFile.now()).append("  -->image:").append(paramName+"...")
            .append(image.getOriginalFilename()).append("\n");
        }

        try {
        	//生成PDF文件
            String targetPath = pdfService.doGeneratePdf(loggerBuffer, basicInfo, number, changeContent,
            		effect, reason, signInfo, sendDepartment, model, imageName, images);
            result.setMsg(targetPath);

        } catch (Exception e) {
            e.printStackTrace();
            result = ResultBean.buildFailureResult(e.getLocalizedMessage());
        } finally {
            logFile.writeLogFile("generatePdf", number, loggerBuffer.toString());
        }

        return result;
    }

    /**
     * 生成技术通知单PDF
     * @param infos
     * @return
     */
    @RequestMapping(value = "/technicalNoticePdf", method = RequestMethod.POST)
    public ResultBean doTechnicalNoticePdf(String infos, @RequestParam Map<String, MultipartFile> images) {
    	logger.info("infos:{}", infos);
    	String number = "";
    	String name = "";
    	String model = "";
    	Object content = "";
		String validPeriod = "";
		Object signInfo = "";
		String sendDepartment = "";
    	// 将 JSON 字符串解析为 JSON 数组
        JSONArray jsonArray = JSONArray.parseArray(infos);
        // 遍历 JSON 数组并输出结果
        for (Object obj : jsonArray) {
            JSONObject json = (JSONObject) obj;
            for (String key : json.keySet()) {
            	if(StringUtils.equals(key, "number")) {
            		number = (String) json.get(key);
            	}else if(StringUtils.equals(key, "name")) {
            		name = (String) json.get(key);
            	}else if(StringUtils.equals(key, "model")) {
            		model = (String) json.get(key);
            	}else if(StringUtils.equals(key, "content")) {
            		content = json.get(key);
            	}else if(StringUtils.equals(key, "validPeriod")) {
            		validPeriod = (String) json.get(key);
            	}else if(StringUtils.equals(key, "signInfo")) {
            		signInfo = json.get(key);
            	}else if(StringUtils.equals(key, "sendDepartment")) {
            		sendDepartment = (String) json.get(key);
            	}
            }
        }
        ResultBean result = ResultBean.buildSuccessResult();
        logger.info("number:{}", number);
        logger.info("name:{}", name);
        logger.info("model:{}", model);
        logger.info("content:{}", content);
        logger.info("validPeriod:{}", validPeriod);
        logger.info("signInfo:{}", signInfo);
        logger.info("sendDepartment:{}", sendDepartment);
        StringBuffer loggerBuffer = new StringBuffer();
        loggerBuffer.append(logFile.now()).append("----->生成PDF开始<-----").append("\n");
        loggerBuffer.append(logFile.now()).append("  -->number:").append(number).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->name:").append(name).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->model:").append(model).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->content:").append(content).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->validPeriod:").append(validPeriod).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->signInfo:").append(signInfo).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->sendDepartment:").append(sendDepartment).append("\n");
        
        for (Map.Entry<String, MultipartFile> entry : images.entrySet()) {
            String paramName = entry.getKey(); // 获取参数名
            MultipartFile image = entry.getValue(); // 获取文件对象
            loggerBuffer.append(logFile.now()).append("  -->image:").append(paramName+"...")
            .append(image.getOriginalFilename()).append("\n");
        }
        
        try {
        	//生成PDF文件
            String targetPath = pdfService.doTechnicalNoticePdf(loggerBuffer, number, name, 
            		model, content, validPeriod, signInfo, sendDepartment, images);
            result.setMsg(targetPath);
        } catch (Exception e) {
            e.printStackTrace();
            result = ResultBean.buildFailureResult(e.getLocalizedMessage());
        } finally {
            logFile.writeLogFile("generateTechnicalNoticePdf", number, loggerBuffer.toString());
        }

        return result;
    }
    
    /**
     * word签名
     * @param infos
     * @param wordFile
     * @return
     */
    @RequestMapping(value = "/orderTechnicalWord", method = RequestMethod.POST)
    public ResultBean signOrderTechnicalWord(String infos, @RequestPart("wordFile") MultipartFile wordFile) {
    	logger.info("infos:{}", infos);
    	String number = "";
    	String name = "";
		Object signInfo = "";
		String sendDepartment = "";
    	// 将 JSON 字符串解析为 JSON 数组
        JSONArray jsonArray = JSONArray.parseArray(infos);
        // 遍历 JSON 数组并输出结果
        for (Object obj : jsonArray) {
            JSONObject json = (JSONObject) obj;
            for (String key : json.keySet()) {
            	if(StringUtils.equals(key, "number")) {
            		number = (String) json.get(key);
            	}else if(StringUtils.equals(key, "name")) {
            		name = (String) json.get(key);
            	}else if(StringUtils.equals(key, "signInfo")) {
            		signInfo = json.get(key);
            	}else if(StringUtils.equals(key, "sendDepartment")) {
            		sendDepartment = (String) json.get(key);
            	}
            }
        }
        ResultBean result = ResultBean.buildSuccessResult();
        logger.info("number:{}", number);
        logger.info("name:{}", name);
        logger.info("signInfo:{}", signInfo);
        logger.info("sendDepartment:{}", sendDepartment);
        logger.info("wordFile:{}", wordFile.getOriginalFilename());
        StringBuffer loggerBuffer = new StringBuffer();
        loggerBuffer.append(logFile.now()).append("----->签名开始<-----").append("\n");
        loggerBuffer.append(logFile.now()).append("  -->number:").append(number).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->name:").append(name).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->signInfo:").append(signInfo).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->sendDepartment:").append(sendDepartment).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->wordFile:").append(wordFile.getOriginalFilename()).append("\n");
        
        try {
        	//生成PDF文件
            String targetPath = pdfService.signOrderTechnicalWord(loggerBuffer, number, name, 
            		signInfo, sendDepartment, wordFile);
            result.setMsg(targetPath);
        } catch (Exception e) {
            e.printStackTrace();
            result = ResultBean.buildFailureResult(e.getLocalizedMessage());
        } finally {
            logFile.writeLogFile("signOrderTechnicalWord", number, loggerBuffer.toString());
        }

        return result;
    	
    }
    
    /**
     * 生成工艺更改单PDF
     * @param infos
     * @param images
     * @return
     */
    @RequestMapping(value = "/processChangePdf", method = RequestMethod.POST)
    public ResultBean generateProcessChangePdf(String infos) {
    	logger.info("infos:{}", infos);
    	String number = "";
    	String processNumber = "";
    	String processName = "";
    	String model = "";
		Object changeContent = "";
		String reason = "";
		Object signInfo = "";
    	// 将 JSON 字符串解析为 JSON 数组
        JSONArray jsonArray = JSONArray.parseArray(infos);
        // 遍历 JSON 数组并输出结果
        for (Object obj : jsonArray) {
            JSONObject json = (JSONObject) obj;
            for (String key : json.keySet()) {
            	if(StringUtils.equals(key, "number")) {
            		number = (String) json.get(key);
            	}else if(StringUtils.equals(key, "processNumber")) {
            		processNumber = (String) json.get(key);
            	}else if(StringUtils.equals(key, "processName")) {
            		processName = (String) json.get(key);
            	}else if(StringUtils.equals(key, "model")) {
            		model = (String) json.get(key);
            	}else if(StringUtils.equals(key, "changeContent")) {
            		changeContent = json.get(key);
            	}else if(StringUtils.equals(key, "reason")) {
            		reason = (String) json.get(key);
            	}else if(StringUtils.equals(key, "signInfo")) {
            		signInfo = json.get(key);
            	}
            }
        }
        ResultBean result = ResultBean.buildSuccessResult();
        logger.info("number:{}", number);
        logger.info("processNumber:{}", processNumber);
        logger.info("processName:{}", processName);
        logger.info("model:{}", model);
        logger.info("changeContent:{}", changeContent);
        logger.info("reason:{}", reason);
        logger.info("signInfo:{}", signInfo);
        StringBuffer loggerBuffer = new StringBuffer();
        loggerBuffer.append(logFile.now()).append("----->生成PDF开始<-----").append("\n");
        loggerBuffer.append(logFile.now()).append("  -->number:").append(number).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->processNumber:").append(processNumber).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->processName:").append(processName).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->model:").append(model).append("\n");
        loggerBuffer.append(logFile.now()).append("  -->reason:").append(reason).append("\n");
        
        try {
        	//生成PDF文件
            String targetPath = pdfService.processChangePdf(loggerBuffer, number, processNumber, 
            		processName, model, changeContent, reason, signInfo);
            result.setMsg(targetPath);

        } catch (Exception e) {
            e.printStackTrace();
            result = ResultBean.buildFailureResult(e.getLocalizedMessage());
        } finally {
            logFile.writeLogFile("processChangePdf", number, loggerBuffer.toString());
        }

        return result;
    }
    
    /**
     * 生成生产领用配套单PDF
     * @param infos
     * @return
     */
    @RequestMapping(value = "/productionSupportingPdf", method = RequestMethod.POST)
    public ResultBean generateProductionSupportingPdf(String infos) {
    	logger.info("infos:{}", infos);
    	String basicInfo = "";
		Object contents = "";
    	// 将 JSON 字符串解析为 JSON 数组
        JSONArray jsonArray = JSONArray.parseArray(infos);
        // 遍历 JSON 数组并输出结果
        for (Object obj : jsonArray) {
            JSONObject json = (JSONObject) obj;
            for (String key : json.keySet()) {
            	if(StringUtils.equals(key, "basicInfo")) {
            		basicInfo = (String) json.get(key);
            	}else if(StringUtils.equals(key, "contents")) {
            		contents = json.get(key);
            	}
            }
        }
        ResultBean result = ResultBean.buildSuccessResult();
        logger.info("basicInfo:{}", basicInfo);
        logger.info("contents:{}", contents);
        StringBuffer loggerBuffer = new StringBuffer();
        loggerBuffer.append(logFile.now()).append("----->生成PDF开始<-----").append("\n");
        loggerBuffer.append(logFile.now()).append("  -->basicInfo:").append(basicInfo).append("\n");
        
        try {
        	//生成PDF文件
            String targetPath = pdfService.productionSupportingPdf(loggerBuffer, basicInfo, contents);
            result.setMsg(targetPath);

        } catch (Exception e) {
            e.printStackTrace();
            result = ResultBean.buildFailureResult(e.getLocalizedMessage());
        } finally {
            logFile.writeLogFile("productionSupportingPdf", "productionSupportingPdf", loggerBuffer.toString());
        }

        return result;
    }
}
